<template>
  <el-upload
    ref="upload"
    :action="uploadUrl"
    :auto-upload="true"
    :headers="headers"
    :on-success="uploadSuccess"
    :data="params"
    :file-list="fileList"
    :on-remove="handleRemove"
  >
    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
  </el-upload>
</template>

<script>
export default {
  name: 'FtpUpload',
  props: {
    value: {
      required: false,
      type: [String, Array],
      default: ''
    },
    dir: {
      required: false,
      type: String,
      default: ''
    },
    fileName: {
      required: false,
      type: String,
      default: ''
    },
    multiple: {
      required: false,
      default: false,
      type: Boolean
    }
  },
  data() {
    return {
      uploadUrl: process.env.VUE_APP_BASE_API + '/upms/config/ftpUpload'
    }
  },
  computed: {
    params() {
      return {
        dir: this.dir,
        fileName: this.fileName
      }
    },
    headers() {
      const map = {}
      map[process.env.VUE_APP_TOKEN_NAME] = this.$store.state.user.token
      return map
    },
    fileList: {
      get() {
        return this.value ? this.value.split(',').map(s => {
          return {
            name: s,
            url: s
          }
        }) : []
      },
      set(val) {
        this.$emit('input', val.map(s => s.url).join(','))
      }
    }
  },
  mounted() {
  },
  methods: {
    uploadSuccess(data) {
      this.$message({ type: data.code === 200200 ? 'success' : 'error', message: data.msg || '上传成功' })
      if (data.code === 200200) {
        this.$emit('success')
        if (this.multiple) {
          this.fileList.push({
            name: data.data,
            url: data.data
          })
        } else {
          this.fileList = [
            {
              name: data.data,
              url: data.data
            }
          ]
        }
      }
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    }
  }
}
</script>

<style>

</style>
